//
//  HomeCollectionViewCell.m
//  Topit
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "HomeCollectionViewCell.h"
#import "HomeTableViewCell.h"
#import "YXYNetWorkTool.h"
#import "URLManager.pch"
#import "MJRefresh.h"
#import "YXYSkipViewController.h"
@implementation HomeCollectionViewCell

-(void)dealloc {
    [_tableView release];
    [_dataSource release];
    _delegate = nil;
    _skipDelegate = nil;
    _nineSkipDelegate = nil;
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.tableView];
        [self getData];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [self.tableView nightMode];
    [self.tableView reloadData];
}


-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes {
    
}

-(void)getData {
    if ([SAReachabilityManager sharedReachabilityManager].currentReachabilityStatus == NotReachable) {
        [ProgressHUD showError:@"请检查网络"];
        return;
    }
    if ([SAReachabilityManager sharedReachabilityManager].currentReachabilityStatus == ReachableViaWWAN) {
        [ProgressHUD show:@"您正处于非WIFI状态下"];
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
   [YXYNetWorkTool getWithUrl:kHomeGETURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
       NSArray *array = result[@"item"];
       for (NSDictionary *dic in array) {
           HomeModel *homeModel = [[HomeModel alloc] initWithDataSource:dic];
           [_dataSource addObject:homeModel];
           [homeModel release];
       }
       [hud hide:YES afterDelay:1];
       dispatch_async(dispatch_get_main_queue(), ^{
           [_tableView reloadData];
       });
   } fail:^(NSError *error) {
       [hud hide:YES];
       [ProgressHUD showError:@"请检查网络"];
   }];
    
}
//底部刷新
- (void) getFoot {
    NSString *num = [NSString stringWithFormat:@"%d", _number];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:num, @"offset", nil];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.labelText = @"正在加载";
    hud.mode = MBProgressHUDModeIndeterminate;
    [YXYNetWorkTool getWithUrl:kHomeFootGETURL parameter:dic httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSArray *array = result[@"item"];
        for (NSDictionary *dic in array) {
            HomeModel *homeModel = [[HomeModel alloc] initWithDataSource:dic];
            [_dataSource addObject:homeModel];
            [homeModel release];
        }
        [hud hide:YES afterDelay:1];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    } fail:^(NSError *error) {
        [ProgressHUD showError:@"请检查网络"];
        [hud hide:YES];
    }];
}
-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}
//当滑动到底部刷新
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    CGFloat currentOffset = offset.y + bounds.size.height - inset.bottom;
    CGFloat maximumOffset = size.height;
    
    if ((int)currentOffset == (int)maximumOffset) {
        _number += 10;
        [self getFoot];
    }
    if (currentOffset == 14980) {
        UIAlertView *allert = [[UIAlertView alloc] initWithTitle:@"别滑了" message:@"屁股疼" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [allert show];
        
    }
}

#pragma mark - tableView
- (UITableView *)tableView {
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 55, self.frame.size.width, self.frame.size.height - 58) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        //添加刷新
        [self addheader];
        
        [_tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"HomeTableViewCellIdentifier"];
        [_tableView registerClass:[YXYFourImageTableViewCell class] forCellReuseIdentifier:@"YXYFourImageTableViewCellIdentifier"];
        [_tableView registerClass:[YXYNineImageTableViewCell class] forCellReuseIdentifier:@"YXYNineImageTableViewCellIdentifier"];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
        [_tableView release];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeModel *homeModle = self.dataSource[indexPath.row];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *passWord = [user objectForKey:@"NightMode"];
    
    if (self.dataSource.count > indexPath.row) {
        
        if (homeModle.dataSource.count == 1) {
            HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCellIdentifier" forIndexPath:indexPath];
            [cell setHomeModel:self.dataSource[indexPath.row]];
            if ([passWord isEqualToString:@"Night"]) {
                cell.backgroundColor = [UIColor colorWithHue:34 / 255.0 saturation:34 / 255.0 brightness:34 / 255.0 alpha:1];
            }else {
                cell.backgroundColor = [UIColor whiteColor];
            }
            return cell;
        }else if (homeModle.dataSource.count == 4) {
            
            YXYFourImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXYFourImageTableViewCellIdentifier" forIndexPath:indexPath];
            cell.delegate = self;
//            [cell.collectionView reloadData];
            [cell setHomeModel:self.dataSource[indexPath.row]];
            if ([passWord isEqualToString:@"Night"]) {
                cell.backgroundColor = [UIColor colorWithHue:34 / 255.0 saturation:34 / 255.0 brightness:34 / 255.0 alpha:1];
            }else {
                cell.backgroundColor = [UIColor whiteColor];
            }
            return cell;
        }else {
            YXYNineImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXYNineImageTableViewCellIdentifier"];
            [cell setHomeModel:self.dataSource[indexPath.row]];
            cell.nineSkipDelegate = self;
            if ([passWord isEqualToString:@"Night"]) {
                cell.backgroundColor = [UIColor colorWithHue:34 / 255.0 saturation:34 / 255.0 brightness:34 / 255.0 alpha:1];
            }else {
                cell.backgroundColor = [UIColor whiteColor];
            }
            return cell;
        }
    }
    return nil;
}
//点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HomeModel *homeModel = _dataSource[indexPath.row];
    if ([homeModel.name isEqualToString:@"热门话题"]) {
       [self.delegate nextDidPressWithURl:homeModel.next];
    }else {
        [self.delegate selectionDidPressWithURL:homeModel.next];
    }
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeModel *homeModel = self.dataSource[indexPath.row];
    if (homeModel.dataSource.count == 1) {
        return 280;
    }else if (homeModel.dataSource.count == 4) {
        return 450;
    }else if (homeModel.dataSource.count == 9){
        return 450;
    }
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - 刷新
-(void)addheader {
    [_tableView addHeaderWithCallback:^{
        [_dataSource removeAllObjects];
        [self getData];
        [_tableView reloadData];
        [_tableView headerEndRefreshing];
    }];
}


#pragma mark - skipDelegate
- (void)skipDidPress:(NSString *)url {
    [self.skipDelegate skipDidPress:url];

}

- (void)nineImagePressSkipWithURL:(NSString *)url {
    [self.nineSkipDelegate nineImagePressSkipWithURL:url];
}
@end
